﻿using CKS.PLC.Core;
using CKS.PLC.Core.Siemens;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Infrastructure.Helper;
using ZR.Model.Models.ProductionControl;


namespace CKS.PLC.Core.Event
{
    public static class EventBus
    {
        /// <summary>
        /// log队列
        /// </summary>
        public static ConcurrentQueue<string> logQueues = new ConcurrentQueue<string>();

        /// <summary>
        /// 当错误状态变更触发
        /// </summary>

        public static event Action<ISiemensClient, int> OnPlcHeart;

        public static event Action<string> OnPLCUpdate;


        internal static void PlcHeart(ISiemensClient plcClient, int plcHeartValue)
        {
            OnPlcHeart?.Invoke(plcClient, plcHeartValue);
        }

        public static void AddLogInfoToQueues(string msg) {
            LogHelper.WritePlcLogInfo(msg);
            msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $" Info [{Thread.CurrentThread.ManagedThreadId}] | " + msg;
            logQueues.Enqueue(msg);
        }

        public static void AddLogErrorToQueues(string msg) {
            LogHelper.WritePlcLogError(msg);
            msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + $" Error [{Thread.CurrentThread.ManagedThreadId}] | " + msg;
            logQueues.Enqueue(msg);
        }

        public static void AddLogToQueues(string msg, CksPlcDataPosition position = null, bool isShowPostion = false) {
            if (position != null && isShowPostion) {
                msg = $"PlcID：{position.PlcId}-{position.WorkStationCode}，DB块：{position.BlockDb}，点位：{position.BytePosition}，ActionType：{position.EffectType.ToString()}，ActionKey：{position.ActionKey}，{msg}";
            } else if(position != null) {
                msg = $"{position.WorkStationCode}，{msg}";
            }
            LogHelper.WritePlcLogInfo(msg);
            msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + msg;
            logQueues.Enqueue(msg);
        }

    }
}
